import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getSystemInfo, checkNetworkStatus } from '../utils/common'
import Storage from '../utils/storage'

export const useAppStore = defineStore('app', () => {
  // 系统信息
  const systemInfo = ref<UniNamespace.GetSystemInfoSuccessCallbackResult | null>(null)
  
  // 网络状态
  const networkType = ref<string>('unknown')
  
  // 应用主题
  const theme = ref<'light' | 'dark'>('light')
  
  // 语言设置
  const locale = ref<'zh-CN' | 'en-US'>('zh-CN')
  
  // 用户信息
  const userInfo = ref<any>(null)
  
  // 是否已登录
  const isLoggedIn = computed(() => !!userInfo.value)
  
  // 应用版本
  const appVersion = ref('1.0.0')
  
  // 启动页显示状态
  const splashVisible = ref(true)

  /**
   * 初始化应用
   */
  const initApp = async () => {
    try {
      // 获取系统信息
      systemInfo.value = await getSystemInfo()
      
      // 获取网络状态
      const network = await checkNetworkStatus()
      networkType.value = network.networkType
      
      // 从本地存储恢复主题设置
      const savedTheme = Storage.get<'light' | 'dark'>('theme')
      if (savedTheme) {
        theme.value = savedTheme
      }
      
      // 从本地存储恢复语言设置
      const savedLocale = Storage.get<'zh-CN' | 'en-US'>('locale')
      if (savedLocale) {
        locale.value = savedLocale
      }
      
      // 从本地存储恢复用户信息
      const savedUserInfo = Storage.get('userInfo')
      if (savedUserInfo) {
        userInfo.value = savedUserInfo
      }
      
      // 监听网络状态变化
      uni.onNetworkStatusChange((res) => {
        networkType.value = res.networkType
      })
      
      console.log('App initialized successfully')
    } catch (error) {
      console.error('App initialization failed:', error)
    } finally {
      // 隐藏启动页
      setTimeout(() => {
        splashVisible.value = false
      }, 2000)
    }
  }

  /**
   * 设置主题
   */
  const setTheme = (newTheme: 'light' | 'dark') => {
    theme.value = newTheme
    Storage.set('theme', newTheme)
  }

  /**
   * 设置语言
   */
  const setLocale = (newLocale: 'zh-CN' | 'en-US') => {
    locale.value = newLocale
    Storage.set('locale', newLocale)
  }

  /**
   * 设置用户信息
   */
  const setUserInfo = (info: any) => {
    userInfo.value = info
    Storage.set('userInfo', info)
  }

  /**
   * 清除用户信息
   */
  const clearUserInfo = () => {
    userInfo.value = null
    Storage.remove('userInfo')
    Storage.remove('token')
  }

  /**
   * 更新网络状态
   */
  const updateNetworkStatus = async () => {
    try {
      const network = await checkNetworkStatus()
      networkType.value = network.networkType
    } catch (error) {
      console.error('Failed to update network status:', error)
    }
  }

  return {
    // 状态
    systemInfo,
    networkType,
    theme,
    locale,
    userInfo,
    isLoggedIn,
    appVersion,
    splashVisible,
    
    // 方法
    initApp,
    setTheme,
    setLocale,
    setUserInfo,
    clearUserInfo,
    updateNetworkStatus
  }
})
